<template>
  <el-dialog v-model="visible" title="代码预览" :close-on-click-modal="false"   width="80%" top="5vh" append-to-body class="scrollbar">
    <el-tabs v-model="activeName">
      <el-tab-pane
          v-for="(value, key) in codeList"
          :label="value.fileName"
          :name="value.fileName"
          :key="key"
      >
       <el-link :underline="false"  title="复制" @click="clipboardSuccess(value.content)"  style="float:right;font-size: 14px"><el-icon><DocumentCopy /></el-icon>复制</el-link>
        <pre><code class="hljs" v-html="highlightedCode(value)"></code></pre>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>
</template>

<script setup lang="ts">
import { nextTick, reactive, ref } from "vue";
import { ElMessage, TabsPaneContext } from "element-plus/es";
import {DocumentCopy} from '@element-plus/icons-vue'
import useClipboard from 'vue-clipboard3'
import hljs from 'highlight.js/lib/highlight';
import "highlight.js/styles/github-gist.css";
import java from "highlight.js/lib/languages/java";
import xml from "highlight.js/lib/languages/xml";
import javascript from "highlight.js/lib/languages/javascript";
import sql from "highlight.js/lib/languages/sql";

hljs.registerLanguage("java", java);
hljs.registerLanguage("xml", xml);
hljs.registerLanguage("html", xml);
hljs.registerLanguage("vue", xml);
hljs.registerLanguage("javascript",javascript);
hljs.registerLanguage("sql", sql);

import { usePreviewApi } from "@/api/generator";

const activeName = ref();
const codeList = ref<any>();
const tableIndex = ref<any>();
const handleClick = (tab: TabsPaneContext) => {
  tableIndex.value = tab.index;
};

const visible = ref(false);


const init = (id: number) => {
  visible.value = true;
  getCodeList(id);
};



const getCodeList = (talbeId:any) => {
  usePreviewApi(talbeId).then(res => {
    codeList.value = res.data;
    activeName.value = res.data[0]?.fileName;
  });
};

/** 高亮显示 */
const  highlightedCode = (code:any) =>{
  const vmName = code.fileName
  const language = vmName.substring(vmName.indexOf(".") + 1, vmName.length);
  const result = hljs.highlight(language, code.content || "", true);
  return result.value || '&nbsp;';
};

/** 复制代码成功 */
const clipboardSuccess = async (content:any)=> {
  const { toClipboard } = useClipboard()
  try {
    //复制
    await toClipboard(content)
    ElMessage.success("复制成功");
  } catch (e) {
    //复制失败
    ElMessage.error("复制失败");
  }
};

defineExpose({
  init
});
</script>

<style lang="scss">

</style>
